<template>
    <div class="plan-library-container">
        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form :inline="true" :model="searchForm" class="demo-form-inline">
                <el-form-item label="预案名称">
                    <el-input v-model="searchForm.planName" placeholder="请输入预案名称" clearable style="width: 200px;"></el-input>
                </el-form-item>
                <el-form-item label="企业名称">
                    <el-input v-model="searchForm.companyName" placeholder="请输入企业名称" clearable style="width: 200px;"></el-input>
                </el-form-item>
                <el-form-item label="监管区域">
                    <el-select v-model="searchForm.supervisionArea" placeholder="请选择监管区域" clearable style="width: 180px;">
                        <!-- 这里可以根据实际数据动态生成选项 -->
                        <el-option label="监管区域1" value="1"></el-option>
                        <el-option label="监管区域2" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备案时间">
                    <el-date-picker 
                        v-model="searchForm.recordTimeRange" 
                        type="daterange" 
                        range-separator="至" 
                        start-placeholder="开始日期" 
                        end-placeholder="结束日期" 
                        value-format="yyyy-MM-dd" 
                        style="width: 280px;">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="行政区域">
                    <el-select v-model="searchForm.adminArea" placeholder="请选择行政区域" clearable style="width: 180px;">
                        <!-- 这里可以根据实际数据动态生成选项 -->
                        <el-option label="行政区域1" value="1"></el-option>
                        <el-option label="行政区域2" value="2"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <!-- 单独的按钮行 -->
            <div class="search-buttons">
                <el-button type="primary" size="small" icon="el-icon-search" @click="handleSearch" style="margin-right: 10px;">查询</el-button>
                <el-button size="small" icon="el-icon-refresh" @click="handleReset">重置</el-button>
            </div>
        </el-card>

        <!-- 操作按钮区域 -->
        <div class="button-group">
            <el-button type="primary" size="small" @click="handleAdd">新增</el-button>
            <el-button type="warning" size="small" @click="handleUpdate" :disabled="selectedRows.length !== 1">修改</el-button>
            <el-button type="danger" size="small" @click="handleDelete" :disabled="!hasSelection">删除</el-button>
            <!-- <el-button size="small" @click="handleExport">导出</el-button> -->
        </div>

        <!-- 表格区域 -->
        <el-table 
            v-loading="loading" 
            :data="tableData" 
            style="width: 100%" 
            border 
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="序号" width="80" align="center">
                <template slot-scope="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column prop="planName" label="预案名称" min-width="200"></el-table-column>
            <el-table-column prop="companyName" label="企业名称" min-width="180"></el-table-column>
            <el-table-column prop="recordTime" label="备案时间" width="180">
                <template slot-scope="scope">
                    {{ scope.row.recordTime }}
                </template>
            </el-table-column>
            <el-table-column prop="recordNumber" label="备案编号" min-width="200"></el-table-column>
            <el-table-column prop="riskLevel" label="风险级别" width="120">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.riskLevel === '一般-大气'" type="info">{{ scope.row.riskLevel }}</el-tag>
                    <el-tag v-else-if="scope.row.riskLevel === '一般-水'" type="info">{{ scope.row.riskLevel }}</el-tag>
                    <el-tag v-else-if="scope.row.riskLevel === '较大-大气'" type="warning">{{ scope.row.riskLevel }}</el-tag>
                    <el-tag v-else-if="scope.row.riskLevel === '较大-水'" type="warning">{{ scope.row.riskLevel }}</el-tag>
                    <el-tag v-else-if="scope.row.riskLevel === '重大-大气'" type="danger">{{ scope.row.riskLevel }}</el-tag>
                    <el-tag v-else-if="scope.row.riskLevel === '重大-水'" type="danger">{{ scope.row.riskLevel }}</el-tag>
                    <span v-else>{{ scope.row.riskLevel }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="legalPersonSignTime" label="法人签署时间" width="180"></el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
                <template slot-scope="scope">
                    <el-button type="text" @click="handleEdit(scope.row)">详情</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <div class="pagination-container" v-if="total > 0">
            <el-pagination
                background
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="pageSize"
                :current-page="pageNum"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            ></el-pagination>
        </div>

        <!-- 弹窗组件 -->
        <plan-dialog
            :dialog-visible.sync="dialogVisible"
            :dialog-type="dialogType"
            :plan-data="currentPlanData"
            @submit="handleDialogSubmit"
        ></plan-dialog>
    </div>
</template>

<script>
import PlanDialog from './dialog.vue';

export default {
    name: 'PlanLibrary',
    components: {
        PlanDialog
    },
    data() {
        return {
            loading: false,
            searchForm: {
                planName: '',
                companyName: '',
                supervisionArea: '',
                recordTimeRange: [],
                adminArea: ''
            },
            tableData: [
                // 模拟数据
                {
                    id: 1,
                    planName: '某污水处理厂应急预案',
                    companyName: '某县污水处理厂',
                    recordTime: '2023-01-15',
                    recordNumber: '一般-大气（GDM-1）',
                    riskLevel: '一般-大气',
                    legalPersonSignTime: '2023-01-20'
                },
                {
                    id: 2,
                    planName: '某污水处理厂应急预案',
                    companyName: '某县污水处理厂',
                    recordTime: '2023-02-10',
                    recordNumber: '一般-水（GDM-1）',
                    riskLevel: '一般-水',
                    legalPersonSignTime: '2023-02-15'
                },
                {
                    id: 3,
                    planName: '某污水处理厂应急预案',
                    companyName: '某市污水处理厂',
                    recordTime: '2023-03-05',
                    recordNumber: '较大-水（GDM-1）',
                    riskLevel: '较大-水',
                    legalPersonSignTime: '2023-03-10'
                }
            ],
            pageNum: 1,
            pageSize: 10,
            total: 3,
            selectedRows: [],
            hasSelection: false,
            // 弹窗相关
            dialogVisible: false,
            dialogType: 'view', // view 或 edit
            currentPlanData: {}
        }
    },
    created() {
        this.getList();
    },
    methods: {
        // 获取列表数据
        async getList() {
            this.loading = true;
            try {
                // 这里应该调用API获取数据
                // const res = await getPlanLibraryList({ ...this.searchForm, pageNum: this.pageNum, pageSize: this.pageSize });
                // this.tableData = res.rows;
                // this.total = res.total;
                
                // 模拟API调用延迟
                setTimeout(() => {
                    this.loading = false;
                }, 300);
            } catch (error) {
                this.loading = false;
                this.$message.error('获取数据失败');
                console.error(error);
            }
        },
        
        // 处理查询
        handleSearch() {
            this.pageNum = 1;
            this.getList();
        },
        
        // 处理重置
        handleReset() {
            this.searchForm = {
                planName: '',
                companyName: '',
                supervisionArea: '',
                recordTimeRange: [],
                adminArea: ''
            };
            this.pageNum = 1;
            this.getList();
        },
        
        // 处理新增
        handleAdd() {
            // 新增预案，打开弹窗并设置为空表单
            this.dialogType = 'edit';
            // 设置为空对象，这样表单就会显示为空
            this.currentPlanData = {};
            this.dialogVisible = true;
        },
        
        // 处理编辑/详情
        handleEdit(row) {
            // 查看预案详情
            this.dialogType = 'view';
            // 模拟获取详情数据
            this.currentPlanData = this.mockGetPlanDetail(row.id);
            this.dialogVisible = true;
        },
        
        // 处理修改
        handleUpdate() {
            if (this.selectedRows.length !== 1) {
                this.$message.warning('请选择一条记录进行修改');
                return;
            }
            // 修改预案
            this.dialogType = 'edit';
            // 模拟获取详情数据
            this.currentPlanData = this.mockGetPlanDetail(this.selectedRows[0].id);
            this.dialogVisible = true;
        },
        
        // 处理弹窗提交
        handleDialogSubmit(data) {
            // 提交修改的数据
            this.$confirm('确定要保存修改吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 这里应该调用API保存数据
                console.log('保存数据:', data);
                this.$message.success('保存成功');
                this.getList();
            }).catch(() => {});
        },
        
        // 模拟获取预案详情
        mockGetPlanDetail(id) {
            // 根据ID获取模拟的详情数据
            const row = this.tableData.find(item => item.id === id);
            // 返回模拟的详细数据
            return {
                ...row,
                unitName: row.companyName,
                orgCode: `ORG${id}0001`,
                legalPerson: '张三',
                legalPersonPhone: '13800138000',
                contactPerson: '李四',
                contactPhone: '13900139000',
                faxNumber: '023-68686868',
                email: 'test@example.com',
                planType: '1',
                adminArea: '1',
                address: '某省某市某区某路123号',
                longitude: 106.5542,
                latitude: 29.5630,
                version: 'V1.0',
                comprehensiveRiskLevel: '1',
                airRiskLevel: '1',
                airQ: '1',
                airM: '1',
                airE: '1',
                waterRiskLevel: '1',
                waterQ: '1',
                waterM: '1',
                waterE: '1',
                isFreeTradeZone: '0',
                declarationDate: row.recordTime,
                signer: '张三',
                auditTime: row.recordTime,
                auditBureau: '1'
            };
        },
        
        // 处理删除
        handleDelete() {
            this.$confirm('确定要删除选中的预案吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 删除逻辑
                this.$message.success('删除成功');
                this.getList();
            }).catch(() => {});
        },
        
        // 处理导出
        handleExport() {
            // 导出逻辑
            this.$message.info('导出功能待实现');
        },
        
        // 处理表格选择变化
        handleSelectionChange(val) {
            this.selectedRows = val;
            this.hasSelection = val.length > 0;
        },
        
        // 处理分页大小变化
        handleSizeChange(val) {
            this.pageSize = val;
            this.getList();
        },
        
        // 处理页码变化
        handleCurrentChange(val) {
            this.pageNum = val;
            this.getList();
        }
    }
}
</script>

<style scoped>
.plan-library-container {
    padding: 20px;
}

.search-card {
    margin-bottom: 20px;
}

.button-group {
    margin-bottom: 20px;
}

.button-group .el-button {
    margin-right: 10px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>